import * as c from '@/services/consts';
// import * as apiServer from '@/services/vpnServer';
import * as api from '@/services/checkTask';
import * as apiNode from '@/services/node';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  ClockCircleOutlined,
  CloseCircleFilled,
  EditOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Badge,
  Button,
  Col,
  Descriptions,
  List,
  message,
  Popconfirm,
  Row,
  Space,
  Tag,
  Tooltip,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import VpnServerBatchRemarkForm from './BatchRemarkForm';
import dayjs from 'dayjs';
import * as utils from '@/utils/utils';
import { ProDescriptions } from '@ant-design/pro-components';

type VpnServerFormProps = {
  visible: boolean;
  ver: string | undefined;
  groupId: string | undefined;
  onCancel: () => void;
  onCancelAndReload: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, onCancelAndReload, ver, groupId } = props;

  if (!visible) {
    return null;
  }

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const actionServerRef = useRef<ActionType>();
  const { hasRight } = useModel('useAuthModel');
  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<API.CheckTaskReport | undefined>(undefined);
  const [selectIds, setSelectIds] = useState<any[]>([]);
  // const [formVisible, setFormVisible] = useState<boolean>(false);
  const [formNodeVisible, setFormNodeVisible] = useState<boolean>(false);
  const [formCdnVisible, setFormCdnVisible] = useState<boolean>(false);
  const [formBridgeVisible, setFormBridgeVisible] = useState<boolean>(false);

  const [formBatchGroupVisible, setFormBatchGroupVisible] =
    useState<boolean>(false);
  const [formBatchRemarkVisible, setFormBatchRemarkVisible] =
    useState<boolean>(false);
  const [currentServer, setCurrentServer] = useState<API.VpnServer | undefined>(
    undefined,
  );
  const [currentNode, setCurrentNode] = useState<API.Node | undefined>(
    undefined,
  );
  const [serverChecks, setServerChecks] = useState<
    API.VpnServerCheckIpReport[] | undefined
  >(undefined);

  let tableGroupTitle: string = '';
  let tableGroupFont: string = 'normal';

  
  const {setXrayConfigPublish} = useModel('useGlobalModel', (model) => ({
    setXrayConfigPublish: model.setXrayConfigPublish,
  }));

  const loadData = async () => {
    const result = await api.report({ ver, groupId });
    if (result && result.success) {
      setDataSource(result);
    }
    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleChangeStatus = async (status: boolean) => {
    if (selectIds.length < 1) return;
    // console.log({ keys: selectIds, status: status });
    // const result = await apiServer.status({ keys: selectIds, status: status });
    const result = await apiNode.status({ keys: selectIds, status: status });
    if (result && result.success === true) {
      setXrayConfigPublish(true);
      setSelectIds([]);
      actionRef.current?.clearSelected?.();
      setMyloading(true);
      loadData();
      // actionRef.current?.reload();
    }
  };

  const handleFormBatchGroupSubmit = async (groupIds: string[]) => {
    // console.log({ keys: selectIds, groupIds: groupIds });
    // result = await apiServer.groups({ keys: selectIds, groupIds: groupIds });    
    const result = await apiNode.groups({ keys: selectIds, groupIds: groupIds });
    if (result && result.success === true) {
      setXrayConfigPublish(true);
      actionRef.current?.clearSelected?.();
      setFormBatchGroupVisible(false);
      setMyloading(true);
      loadData();
      // actionRef.current?.reload();
    }
  };

  const handleFormBatchRemarkSubmit = async (remark: string) => {
    let result: API.Result;
    // result = await apiServer.remarks({ keys: selectIds, remark: remark });
    result = await apiNode.remarks({ keys: selectIds, remark: remark });
    if (result && result.success === true) {
      actionRef.current?.clearSelected?.();
      setFormBatchRemarkVisible(false);
      // setMyloading(true);
      // loadData();
      // actionRef.current?.reload();
    }
  };

  // const handleFormSubmit = async (record: API.VpnServer) => {
  //   if (!record) {
  //     message.error('参数出错');
  //     return;
  //   }
  //   let result: API.Result = await apiServer.update({
  //     ...currentServer,
  //     ...record,
  //   });

  //   if (result && result.success === true) {
  //     setCurrentServer(undefined);
  //     setFormVisible(false);
  //     setMyloading(true);
  //     loadData();
  //   }
  // };
  
  const handleNodeFormSubmit = async (record: API.Node) => {
    let result: API.Result | undefined = undefined;
    if (currentNode) {
      result = await apiNode.update({
        ...currentNode,
        ...record,
      });
    }

    if (result && result.success === true) {
      setXrayConfigPublish(true);
      setCurrentNode(undefined);
      setFormNodeVisible(false);
      setFormCdnVisible(false);
      setFormBridgeVisible(false);
      setMyloading(true);
      loadData();
    }
  };

  const handleRemove = async (ver: string | undefined) => {
    if (!ver) {
      message.error('无效版本号');
      return;
    }
    const result = await api.remove({ ver: ver });
    if (result.success) {
      onCancelAndReload();
    }
  };

  const clientColumns: ProColumns<API.CheckProgress>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      sorter: true,
      search: false,
      render: (_, record) => {
        return record.server?.status == true ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '在线',
      align: 'center',
      width: 60,
      dataIndex: 'online',
      sorter: true,
      search: false,
      render: (_, record) => {
        return record.server?.online == true ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '检测端',
      width:200,
      dataIndex: 'serverId',
      // render: (_, record) => {
      //   return `${record} [${record.id}]`;
      // },
    },
    {
      title: '检测端IP',
      dataIndex: 'ip',
      width:250,
      render: (_, record) => {
        return <>{record.serverIp} {record.network ? <Tag color='blue'>{record.network}</Tag> : ''}</>;
      },
    },
    {
      title: '进度',
      dataIndex: 'percent',
      width:80,
      render: (_, record) => {
        if (record.percent == 100) {
          return '完成';
        } else {
          return record.percent >=0 ? `${record.percent} %` : '--';
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
    },
  ];

  const columns: ProColumns<API.CheckReport>[] = [
    // {
    //   title: '状态',
    //   align: 'center',
    //   width: 60,
    //   dataIndex: 'serverStatus',
    //   hideInTable:!(dataSource?.task?.job == c.CheckJob.CheckNode.value || dataSource?.task?.job == c.CheckJob.SpeedTest.value),
    //   renderText: (val) => {
    //     return val ? (
    //       <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
    //     ) : (
    //       <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
    //     );
    //   },
    // },
    {
      title: '分组',
      dataIndex: 'groupNames',
      width: 150,
      hideInTable:!(dataSource?.task?.job == c.CheckJob.CheckNode.value || dataSource?.task?.job == c.CheckJob.SpeedTest.value),
      render: (_, record) => {
        let text = record.server?.groups?.map((val)=>val.name).join(',');
        if (tableGroupTitle != text) {
          tableGroupFont = tableGroupFont == 'blue' ? 'green' : 'blue';
        }
        tableGroupTitle = text;
        return (<div>
          <div style={{ color: tableGroupFont }}>{text}</div>
          <div><Tag color={record.server?.status == true ? 'blue' : 'error'}>{record.instanceId}</Tag></div>
          <div>{record.server?.name}</div>
        </div>);
      },
    },
    {
      title: '检测结果',
      dataIndex: 'groupNames',
      render: (_, record) => {
        if (!record.data) {
          return <></>;
        }
        let instCheckIps: API.VpnServerCheckIpReport[] = [];
        return record.data.map((item) => {
          let instCheckIp: API.VpnServerCheckIpReport = {
            client: item.ip,//item.bindIp,
            ping: true,
          };
          instCheckIps.push(instCheckIp);
          return (
            <List
              itemLayout="horizontal"
              dataSource={[item]}
              renderItem={(itemIp, index) => (
                <List.Item>
                  <List.Item.Meta style={{marginTop:-18}}
                    // title={
                    //   <Space style={{color:'#777'}}>
                    //   {item.ip}
                    //   {hasRight('node_update') && (dataSource?.task?.job == c.CheckJob.CheckNode.value || dataSource?.task?.job == c.CheckJob.SpeedTest.value) ? (
                    //     <a
                    //       onClick={(e) => {
                    //         if(record.server?.type == c.NodeType.Node.value){
                    //           setFormNodeVisible(true);
                    //           setCurrentNode(record.server);
                    //         }
                    //         else if(record.server?.type == c.NodeType.Cdn.value){
                    //           setFormCdnVisible(true);
                    //           setCurrentNode(record.server);
                    //         }
                    //         else if(record.server?.type == c.NodeType.Bridge.value){
                    //           setFormBridgeVisible(true);
                    //           setCurrentNode(record.server);
                    //         }
                    //       }}
                    //     >
                    //       {' '}
                    //       <EditOutlined />
                    //     </a>
                    //   ) 
                    //   : ''}</Space>
                    // }
                    description={<>                    

                    <Descriptions layout="vertical" column={item.reports.length>12?12:item.reports.length}>
                      <Descriptions.Item labelStyle={{marginBottom:-15}} contentStyle={{marginBottom:-20}} label={
                        <Space style={{color:'#777', fontWeight:'bold'}}>
                        {item.ip}
                        {hasRight('node_update') && (dataSource?.task?.job == c.CheckJob.CheckNode.value || dataSource?.task?.job == c.CheckJob.SpeedTest.value) ? (
                          <a onClick={(e) => {
                              if(record.server?.type == c.NodeType.Node.value){
                                setFormNodeVisible(true);
                                setCurrentNode(record.server);
                              }
                              else if(record.server?.type == c.NodeType.Cdn.value){
                                setFormCdnVisible(true);
                                setCurrentNode(record.server);
                              }
                              else if(record.server?.type == c.NodeType.Bridge.value){
                                setFormBridgeVisible(true);
                                setCurrentNode(record.server);
                              }
                            }}
                          >{' '}<EditOutlined />
                          </a>
                        ) : ''}</Space>
                      }>
                        <Row gutter={item.reports.length>12?12:item.reports.length}>
                        {item.reports?.map((rep) => {
                          return (
                            <Col style={{marginRight:10}}>
                            <Tooltip title={<div style={{maxWidth:900, maxHeight:600, overflow:'auto'}}>{rep.logData?.map((c)=><div>{c}</div>)}</div>} overlayStyle={{minWidth:600, maxWidth: 900}}>
                                <Tag color={rep.ping == true ? 'success' : 'error'} style={{marginRight:-3,width:100}}>
                                  <b>{rep.serverId}</b>{rep.delay == 0 ? <span style={{color:'red'}}>&nbsp;0ms</span> : rep.delay > 0 ? <span style={{color:'#999'}}>&nbsp;{rep.delay}ms</span> :''}
                                </Tag></Tooltip>

                              {dataSource?.task?.job == "speedtest" ? 
                                <Tooltip title={<div style={{maxWidth:300, maxHeight:600, overflow:'auto'}}>
                                  <div>测速服务器国家：{rep.serverCountry}</div>
                                  {/* <div>测速服务器距离：{rep.serverDistance}</div>
                                  <div>测速服务器延迟：{rep.serverLatency}</div> */}
                                  <div>测速服务器出口IP：{rep.exportIp}</div>
                                  </div>} 
                                  overlayStyle={{minWidth:300, maxWidth: 900}}>
                                  <Tag style={{marginRight:4}}>
                                    <ArrowDownOutlined />
                                    {utils.formatRateBit(rep.download)}
                                    &nbsp;
                                    <ArrowUpOutlined />
                                    {utils.formatRateBit(rep.upload)}
                                  </Tag>
                                </Tooltip>
                              : ''}
                            </Col>);
                          })}  
                        </Row>                          
                        </Descriptions.Item>
                    </Descriptions>
                    
                    {/* {item.reports?.map((rep) => {
                      instCheckIp.ping = instCheckIp.ping && rep.ping ? true : false;
                      return (
                          <div style={{marginBottom:5}}>
                          <Space style={{width:250}}>
                            <Tag color={rep.ping == true ? 'success' : 'error'} style={{marginRight:-3,width:240}}>
                              <b>{rep.client}</b>&nbsp;&nbsp;[{rep.ip}] {rep.delay == 0 ? <span style={{color:'red'}}>&nbsp;&nbsp;0ms</span> : rep.delay > 0 ? <span style={{color:'#999'}}>&nbsp;&nbsp;{rep.delay}ms</span> :''}
                            </Tag>

                            {rep.logData ? 
                              <Tooltip title={<div style={{maxWidth:900, maxHeight:600, overflow:'auto'}}>{rep.logData.map((c)=><div>{c}</div>)}</div>} overlayStyle={{minWidth:600, maxWidth: 900}}>
                                <InfoCircleOutlined />
                              </Tooltip>:''}
                          </Space>

                          {dataSource.job == "speedtest" ? 
                            <Space>
                            <Tag style={{marginRight:4}}>
                              <ArrowDownOutlined />
                              {utils.formatRateBit(rep.download)}
                              &nbsp;
                              <ArrowUpOutlined />
                              {utils.formatRateBit(rep.upload)}
                            </Tag>
                              <Tooltip title={<div style={{maxWidth:300, maxHeight:600, overflow:'auto'}}>
                                <div>测速服务器国家：{rep.serverCountry}</div>
                                <div>测速服务器距离：{rep.serverDistance}</div>
                                <div>测速服务器延迟：{rep.serverLatency}</div>
                                <div>测速服务器出口IP：{rep.exportIp}</div>
                                </div>} overlayStyle={{minWidth:300, maxWidth: 900}}>
                                 <InfoCircleOutlined />
                              </Tooltip>
                            </Space> : ''}

                            
                          {dataSource.job == "checkapi" && rep.serverCountry ? 
                            <Tag style={{marginRight:0}}>
                              {rep.serverCountry}
                            </Tag> : ''}

                          </div>
                      );
                    })} */}


                    </>}
                  />
                </List.Item>
              )}
            />
            // <Descriptions
            //   column={2}
            //   style={{ marginBottom: -10 }}
            // >
            //   <Descriptions.Item  style={{width:200}}>
            //     <Tag style={{ margin: 0 }}>IP</Tag>
            //     {item.ip}
            //     {hasRight('node_update') && (dataSource?.job == "checknode" || dataSource?.job == "speedtest") ? (
            //       <a
            //         onClick={(e) => {
            //           if(record.node?.type == c.NodeType.Node.value){
            //             setFormNodeVisible(true);
            //             setCurrentNode(record.node);
            //           }
            //           else if(record.node?.type == c.NodeType.Cdn.value){
            //             setFormCdnVisible(true);
            //             setCurrentNode(record.node);
            //           }
            //           else if(record.node?.type == c.NodeType.Bridge.value){
            //             setFormBridgeVisible(true);
            //             setCurrentNode(record.node);
            //           }
            //         }}
            //       >
            //         {' '}
            //         <EditOutlined />
            //       </a>
            //     ) 
            //     : ''}
            //   </Descriptions.Item>
            //   <Descriptions.Item>
            //     {item.reports?.map((rep) => {
            //       instCheckIp.ping = instCheckIp.ping && rep.ping ? true : false;
            //       return (
            //           <p>
            //           {rep.ping == true ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}
            //           {rep.client}

            //           {dataSource.job == "speedtest" ? 
            //             <Tag color="blue" style={{marginRight:0}}>
            //               <ArrowDownOutlined />
            //               {utils.formatRateBit(rep.download)}
            //               &nbsp;
            //               <ArrowUpOutlined />
            //               {utils.formatRateBit(rep.upload)}                          
            //               <Tooltip title={<div style={{maxWidth:300, maxHeight:600, overflow:'auto'}}>
            //                 <div>测速服务器国家：{rep.serverCountry}</div>
            //                 <div>测速服务器距离：{rep.serverDistance}</div>
            //                 <div>测速服务器延迟：{rep.serverLatency}</div>
            //                 <div>测速服务器出口IP：{rep.exportIp}</div>
            //                 </div>} overlayStyle={{minWidth:300, maxWidth: 900}}>
            //                 {rep.serverLatency} <InfoCircleOutlined />
            //               </Tooltip>
            //             </Tag> : ''}

                        
            //           {dataSource.job == "checkapi" && rep.serverCountry ? 
            //             <Tag color="blue" style={{marginRight:0}}>
            //               {rep.serverCountry}
            //             </Tag> : ''}

            //             {rep.logData ? 
            //               <Tooltip title={<div style={{maxWidth:900, maxHeight:600, overflow:'auto'}}>{rep.logData.map((c)=><div>{c}</div>)}</div>} overlayStyle={{minWidth:600, maxWidth: 900}}>
            //                 <InfoCircleOutlined />
            //               </Tooltip>:''}
            //           </p>
            //       );
            //     })}
            //   </Descriptions.Item>
            // </Descriptions>
          );
        });
      },
    },
  ];

  return (
    <DrawerForm<API.VpnServerCheckModel>
      open={visible}
      title={
        <>
          检测结果 <Tag color="blue">版本：{dataSource?.task?.id}</Tag>{' '}
          <Tag color="blue">下发时间：{dayjs(dataSource?.task?.createTime).format('YYYY-MM-DD HH:mm:ss')}</Tag>{' '}
          <Tag color="blue">创建人：{dataSource?.task?.createUser}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1200}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
      loading={myloading}
    >

      <ProTable<API.VpnServerCheckProgress>
        rowKey="client"
        actionRef={actionRef}
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={clientColumns}
        expandable={undefined}
        dataSource={dataSource?.task?.progresss}
      />



      <ProTable<API.CheckReport>
        rowKey="serverId"
        actionRef={actionServerRef}
        headerTitle={
          <b>
            检测结果　

            {dataSource?.task?.createTime ? dayjs(new Date()).format('YYYY-MM-DD') !=
              dayjs(dataSource?.task?.createTime).format('YYYY-MM-DD') ? <Tag color="#f50">非当天检测结果</Tag> : '' : ''
            }

            <Tag color={utils.getTextRanColor(dataSource?.task?.job ?? '')}>
              {c.getObjectText(c.CheckJobAllOptions, dataSource?.task?.job)}
            </Tag>

            <>{dataSource?.task?.mode ? 
            <Tag color={utils.getTextRanColor(dataSource?.task?.mode ?? '')}>{c.getObjectText(c.CheckModeOptions, dataSource?.task?.mode)}</Tag> 
            : ''}</>

            <Tag color={dataSource?.task?.level == c.CheckLevel.Urgent.value ? '#f50' : '#2db7f5'}>
              {c.getObjectText(c.CheckLevelOptions, dataSource?.task?.level)}
            </Tag>

            　
            {dataSource?.task?.checkBlock == true ? (
              <Tag color="#2db7f5">检测被墙</Tag>
            ) : (
              ''
            )}
          </b>
        }
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={columns}
        expandable={undefined}
        dataSource={dataSource?.reports}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
              <span>
                  <Button onClick={async()=>{
                    setMyloading(true);
                    await loadData();
                  }}>刷新</Button>
              </span>
                <span>
                  <Popconfirm
                    key="delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemove(dataSource?.task?.id);
                    }}
                  >
                    <Button type="primary">删除当前检测</Button>
                  </Popconfirm>
                </span>
                <span>
                  <a
                    target="_blank"
                    key="excel"
                    href={`/admin-api/checktask/export?ver=${
                      ver ? ver : dataSource?.task?.id
                    }`}
                  >
                    <ArrowDownOutlined />
                    下载Excel
                  </a>
                </span>
              </Space>
            </>
          ),
        }}
        rowSelection={!(dataSource?.task?.job == c.CheckJob.CheckNode.value || dataSource?.task?.job == c.CheckJob.SpeedTest.value) ? false : {
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>

            <span>
              {hasRight('node_update') ? (
                <Popconfirm
                  key="disableStatus"
                  title="确定要批量禁用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(false);
                  }}
                >
                  <a>禁用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <Popconfirm
                  key="enableStatus"
                  title="确定要批量启用服务器？"
                  onConfirm={async () => {
                    handleChangeStatus(true);
                  }}
                >
                  <a>启用</a>
                </Popconfirm>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchGroupVisible(true);
                  }}
                >
                  分组
                </a>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('node_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchRemarkVisible(true);
                  }}
                >
                  服务器备注
                </a>
              ) : (
                ''
              )}
            </span>
            
            <span>
                  <a
                    target="_blank"
                    key="export_excel_select"
                    href={`/admin-api/vpnservercheck/export?ver=${
                      ver ? ver : dataSource?.ver
                    }${selectIds?.map((val) => {return "&ids=" + val})}`}
                  >
                    <ArrowDownOutlined />
                    导出Excel
                  </a>
            </span>
          </Space>
        )}
      />

      <VpnServerBatchRemarkForm
        visible={formBatchRemarkVisible}
        onSubmit={handleFormBatchRemarkSubmit}
        onCancel={() => {
          setFormBatchRemarkVisible(false);
        }}
      />
    </DrawerForm>
  );
};

export default VpnServerForm;
